<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="群组ID" prop="gid">
        <el-input
          v-model="queryParams.gid"
          placeholder="请输入群组ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="群名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入群名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成员数量" prop="memberCount">
        <el-input
          v-model="queryParams.memberCount"
          placeholder="请输入成员数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
  
            <el-form-item label="禁止群内私聊" prop="privateChat">
        <el-select
          v-model="queryParams.privateChat"
          placeholder="请选择是否禁止群内私聊"
          clearable
        >
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>   
      <el-form-item label="创建时间" prop="createtime">
        <el-date-picker clearable
          v-model="queryParams.createtime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
  
      

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:group:add']"
        >新增</el-button>
      </el-col>
     
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:group:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="群组id" align="center" prop="gid" />
      <el-table-column label="群名称" align="center" prop="name" />
      <el-table-column label="群头像" align="center" prop="portrait" width="80">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.portrait" 
            :src="getImageUrl(scope.row.portrait)" 
            style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;"
            @error="handleImageError"
          />
          <el-avatar v-else :size="40" icon="el-icon-user-solid"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="成员数量" align="center" prop="memberCount">
        <template slot-scope="scope">
          <el-button type="text" @click="showGroupMembers(scope.row)">{{ scope.row.memberCount }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="regTime" width="180">
      </el-table-column>
      <el-table-column label="全员禁言开关" align="center" prop="mute">
        <template slot-scope="scope">
          <el-tag :type="scope.row.mute == 1 ? 'danger' : 'success'">
            {{ scope.row.mute == 1 ? '开启' : '关闭' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否禁止群内私聊" align="center" prop="privateChat">
        <template slot-scope="scope">
          <el-tag :type="scope.row.privateChat == 1 ? 'warning' : 'success'">
            {{ scope.row.privateChat == 1 ? '禁止' : '允许' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:group:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:group:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改max group member count对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="群名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入群名称" />
        </el-form-item>
        <el-form-item label="头像" prop="portrait">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <img 
              v-if="form.portrait" 
              :src="getImageUrl(form.portrait)" 
              class="avatar" 
              @error="handleImageError"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div v-if="form.portraitPath" class="avatar-url-display">
            <el-button size="mini" type="text" @click="clearAvatar">清除头像</el-button>
          </div>
        </el-form-item>
        <el-form-item label="群主" prop="owner">
          <el-select
            v-model="form.owner"
            placeholder="请选择群主"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userLoading"
            clearable
            style="width: 100%">
            <el-option
              v-for="user in userOptions"
              :key="user.uid"
              :label="user.displayName || user.uid"
              :value="user.uid"/>
          </el-select>
        </el-form-item>
        <el-form-item label="最大成员数" prop="maxMemberCount">
          <el-input v-model="form.maxMemberCount" placeholder="请输入最大成员数" />
        </el-form-item>
        <el-form-item label="扩展字段" prop="extra">
          <el-input v-model="form.extra" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="全员禁言开关" prop="mute">
          <el-select v-model="form.mute" placeholder="请选择全员禁言开关" clearable>
            <el-option label="开启" value="1"></el-option>
            <el-option label="关闭" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否禁止群内私聊" prop="privateChat">
          <el-select v-model="form.privateChat" placeholder="请选择是否禁止群内私聊" clearable>
            <el-option label="禁止" value="1"></el-option>
            <el-option label="允许" value="0"></el-option>
          </el-select>
        </el-form-item>

      
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 群用户信息弹框 -->
    <el-dialog title="群用户信息" :visible.sync="memberDialogVisible" width="900px" append-to-body top="10vh">
      <!-- 添加操作按钮区域 -->
      <div style="margin-bottom: 15px;">
        <el-button type="primary" icon="el-icon-plus" @click="showAddMemberDialog">新增群用户</el-button>
      </div>
      
      <el-table :data="groupMemberList" border @selection-change="handleMemberSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户唯一ID" align="center" prop="userId" />
        <el-table-column label="用户ID" align="center" prop="memberId" />
        <el-table-column label="用户昵称" align="center" prop="nickname" />
        <el-table-column label="加入时间" align="center" prop="joinTime" width="180">
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeSingleMember(scope.row,currentGroup.gid)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="memberDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增群成员弹框 -->
    <el-dialog title="新增群成员" :visible.sync="addMemberDialogVisible" width="500px" append-to-body>
      <el-form ref="addMemberForm" :model="addMemberForm" :rules="addMemberRules" label-width="100px">
        <el-form-item label="选择用户" prop="userId">
          <el-select
              v-model="addMemberForm.userId"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userLoading"
            clearable>
            <el-option
              v-for="user in userOptions"
              :key="user.uid"
              :label="user.displayName || user.uid"
              :value="user.uid">
              <span style="float: left">{{ user.displayName || user.uid }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.userName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddMember(currentGroup.gid)">确 定</el-button>
        <el-button @click="cancelAddMember">取 消</el-button>
      </div>
    </el-dialog>
    </div>

  
</template>
<script>
import { listGroup, getGroup, delGroup, addGroup, updateGroup, listGroupMembers, setGroupOwner, setGroupAdmin, groupMemberAddOrDel } from "@/api/zl/group";
import { listUser } from "@/api/zl/user";

export default {
  name: "Group",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 群组列表数据
      groupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 群用户信息弹框显示状态
      memberDialogVisible: false,
      // 群用户列表数据
      groupMemberList: [],
      // 当前选中的群组信息
      currentGroup: {},
      // 新增群成员弹框显示状态
      addMemberDialogVisible: false,
      // 选中的群成员
      selectedMembers: [],
      // 用户选项列表
      userOptions: [],
      // 用户搜索加载状态
      userLoading: false,
      // 用户是否还有更多数据
      userHasMore: true,
      // 用户总数
      userTotal: 0,
      // 用户分页参数
      userPageNum: 1,
      userPageSize: 10,
      // 当前搜索关键字
      currentSearchQuery: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gid: null,
        name: null,
        portrait: null,
        portraitPath: null,
        owner: null,
        type: null,
        extra: null,
        dt: null,
        memberCount: null,
        memberDt: null,
        createtime: null,
        mute: null,
        joinType: null,
        privateChat: null,
        searchable: null,
        historyMessage: null,
        maxMemberCount: null,
        superGroup: null,
        deleted: null
      },
      // 表单参数
      form: {
        id: null,
        gid: null,
        name: null,
        portrait: null,
        portraitPath: null,
        owner: null,
        type: null,
        extra: null,
        dt: null,
        memberCount: null,
        memberDt: null,
        createtime: null,
        mute: null,
        joinType: null,
        privateChat: null,
        searchable: null,
        historyMessage: null,
        maxMemberCount: null,
        superGroup: null,
        deleted: null,
        memberList: []
      },
      // 新增群成员表单
      addMemberForm: {
        userId: null
      },
      // 表单校验
      rules: {
        gid: [
          { required: true, message: "群组ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "群名称不能为空", trigger: "blur" }
        ]
      },
      // 新增群成员表单校验
      addMemberRules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ]
      }
    };
  },
    created() {
        this.getList()
        // 移除这行，因为upload现在是computed属性
        // this.upload.headers = { Authorization: "Bearer " + this.getToken() };
      },
      methods: { 
          handleSelectScroll(event) {
          const { target } = event
          if (target.scrollTop + target.offsetHeight >= target.scrollHeight - 10) {
            // 接近底部时自动加载更多
            this.loadMoreUsers()
          }
        },
        /** 获取图片完整URL */
        getImageUrl(url) {
          if (!url) return ''
          // 清理URL中的空格和反引号
          url = url.trim().replace(/`/g, '');

          // 如果是OSS的完整URL，通过后端下载接口访问
          if (url.startsWith('https://') && url.includes('aliyuncs.com')) {
            return process.env.VUE_APP_BASE_API + '/common/download?fileName=' + encodeURIComponent(url) + '&delete=false'
          }
          
          // 如果已经是完整的HTTP/HTTPS URL，直接返回
          if (url.startsWith('http://') || url.startsWith('https://')) {
            return url
          }
          
          // 否则拼接BASE_API
          return process.env.VUE_APP_BASE_API + url
        },
        /** 查询max group member count列表 */
        getList() {
          this.loading = true
          listGroup(this.queryParams).then(response => {
            this.groupList = response.rows
            this.total = parseInt(response.total) || 0  // 确保total是数字类型
            this.loading = false
          })
        },
        // 取消按钮
        cancel() {
          this.open = false
          this.reset()
        },
        // 表单重置
        reset() {
          this.form = {
            id: null,
            gid: null,
            name: null,
            portrait: null,
            portraitPath: null,
            owner: null,
            type: null,
            extra: null,
            dt: null,
            memberCount: null,
            memberDt: null,
            createtime: null,
            mute: null,
            joinType: null,
            privateChat: null,
            searchable: null,
            historyMessage: null,
            maxMemberCount: null,
            superGroup: null,
            deleted: null
          }
          // 重置用户相关状态
          this.userOptions = []
          this.userLoading = false
          this.userPageNum = 1
          this.userHasMore = true
          this.currentSearchQuery = ''
          
          // 重置群成员用户相关状态
          this.memberUserOptions = []
          this.memberUserLoading = false
          this.memberUserPageNum = 1
          this.memberUserHasMore = true
          this.currentMemberSearchQuery = ''
          
          this.resetForm("form")
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1
          this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.resetForm("queryForm")
          this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.ids = selection.map(item => item.id)
          this.single = selection.length!==1
          this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
          this.reset()
          this.open = true
          this.title = "添加"
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset()
          const id = row.id || this.ids
          getGroup(id).then(response => {
            this.form = response.data
            this.open = true
            this.title = "修改"
          })
        },
        /* 提交时合并群主 + 群成员 */
        submitForm() {
          this.$refs.form.validate(valid => {
            if (!valid) return;
          // 将群成员ID数组转换为对象数组格式
          const memberListFormatted = (this.form.memberList || []).map(memberId => ({
            member_id: memberId
          }));
            // 构造提交数据
            const payload = { 
              ...this.form, 
              memberList: memberListFormatted  // 使用新的对象数组格式
            };       
            const api = this.form.id ? updateGroup : addGroup;
            api(payload).then(() => {
              this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功');
              this.open = false;
              this.getList();
            });
          });
        },
        // 新增群成员
        submitAddMember(gid){
          this.$refs.addMemberForm.validate(valid => {
            if (!valid) return;
            // 构造memberList数据结构
            const memberList = [{
              member_id: this.addMemberForm.userId
            }];
            
            groupMemberAddOrDel({
              gid: gid,
              memberList: memberList,
              addOrDel: 0
            }).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.addMemberDialogVisible = false;
              this.getGroupMembers(this.currentGroup.gid);
              this.$refs.addMemberForm.resetFields();
            }).catch(() => {});
          });
        },
        cancelAddMember(){  
          this.addMemberDialogVisible = false
          this.$refs.addMemberForm.resetFields()
        },
        /** 删除按钮操作 */
        handleDelete(row) {
          const ids = row.id || this.ids
          this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
            return delGroup(ids)
          }).then(() => {
            this.getList()
            this.$modal.msgSuccess("删除成功")
          }).catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
          this.download('system/group/export', {
            ...this.queryParams
          }, `group_${new Date().getTime()}.xlsx`)
        },
        /** 显示群用户信息 */
        showGroupMembers(row) {
          this.currentGroup = row
          this.memberDialogVisible = true
          // 调用真实API获取群成员数据
          this.getGroupMembers(row.gid)
        },
        showAddMemberDialog(){
          this.addMemberDialogVisible = true
        },
        /** 获取群用户列表 */
        getGroupMembers(groupId) {
          listGroupMembers(groupId).then(response => {
            // 根据后端返回的数据结构处理
            const memberList = response.rows || response.data || []
            // 转换数据格式，适配前端显示
            this.groupMemberList = memberList.map(member => ({
              userId: member.member_id,  // member_id为用户id
              nickname: member.memberName,
              memberId: member.member,
              joinTime: member.time ,
              type: member.type || 0,  // 成员类型
              alias: member.alias || ''  // 群内昵称
            }))
          }).catch(error => {
            console.error('获取群成员列表失败:', error)
            this.$modal.msgError('获取群成员列表失败')
            // 如果API调用失败，清空列表
            this.groupMemberList = []
          })
        },
        /** 设置为群管理员 */
        setGroupAdmin(member) {
          this.$modal.confirm('是否确认设置用户"' + member.nickname + '"为群管理员？').then(() => {
            return setGroupAdmin({
              groupId: this.currentGroup.gid,
              userId: member.userId
            })
          }).then(() => {
            this.$modal.msgSuccess("设置成功")
            this.getGroupMembers(this.currentGroup.gid)
          }).catch(() => {})
        },
        /** 群成员表格多选处理 */
        handleMemberSelectionChange(selection) {
          this.selectedMembers = selection
          this.memberIds = selection.map(item => item.userId)
        },
        /** 移除单个群成员 */
        removeSingleMember(member,gid) {
          console.log(gid)
          this.$modal.confirm('是否确认移除用户"' + member.nickname + '"？').then(() => {
            // 构造memberList数据结构
            const memberList = [{
              member_id: member.userId
            }];
            
            return groupMemberAddOrDel({
              gid: gid,
              memberList: memberList,
              addOrDel: 1
            });
          }).then(() => {
            this.$modal.msgSuccess("移除成功");
            this.getGroupMembers(this.currentGroup.gid);
          }).catch(() => {});
        },
        /** 头像上传成功处理 */
        handleAvatarSuccess(res, file) {
          console.log('上传响应:', res);
          
          if (res.code === 200) {
            // 后端返回的是完整的阿里云OSS URL，需要清理空格和反引号
            let avatarUrl =  res.url;
            let avatarUrlPath =  res.fileName;

            
            // 清理URL中的空格、反引号和双引号
            if (avatarUrl) {
              avatarUrl = avatarUrl.trim().replace(/[`"]/g, '');
            }
            if (avatarUrlPath) {
              avatarUrlPath = avatarUrlPath.trim().replace(/[`"]/g, '');
            }
            
            this.form.portrait = avatarUrl;
            this.form.portraitPath = avatarUrlPath;

            this.$message.success('头像上传成功');
            
            // 强制更新视图
            this.$nextTick(() => {
              this.$forceUpdate();
            });
          } else {
            this.$message.error(res.msg || '上传失败');
          }
        },
        /** 头像上传前校验 */
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
          const isLt2M = file.size / 1024 / 1024 < 2

          if (!isJPG) {
            this.$modal.msgError('上传头像图片只能是 JPG/PNG/GIF 格式!')
          }
          if (!isLt2M) {
            this.$modal.msgError('上传头像图片大小不能超过 2MB!')
          }
          return isJPG && isLt2M
        },
        /** 清除头像 */
        clearAvatar() {
          if (this.form.portraitPath) {
            console.log('当前头像URL:', this.form.portraitPath);
            // 调用后端删除文件接口
            this.deleteFile(this.form.portraitPath).then(() => {
              this.form.portrait = null
              this.$modal.msgSuccess("头像已清除")
            }).catch(() => {
              // 即使删除失败也清除表单字段
              this.form.portraitPath = null
              this.$modal.msgSuccess("头像已清除")
            })
          }
        },
        /** 获取token */
        getToken() {
          return this.$store.getters.token
        },
        /** 删除文件 */
        deleteFile(fileName) {
          return request({
            url: '/common/delete',
            method: 'post',
            data: fileName,
            headers: {
              'Content-Type': 'text/plain'
            }
          })
        },
        /** 处理图片加载错误 */
        handleImageError(event) {
          // 设置默认头像
          event.target.src = require('@/assets/images/profile.jpg')
          // 或者可以隐藏图片：event.target.style.display = 'none'
        },
            /* 搜索用户（用于群主） */
        searchUsers(query) {
          this.searchUserBase(query,1, list => { this.userOptions = list; });
        },
        /* 搜索用户（用于群成员） */
        searchMemberUsers(query) {
          this.searchUserBase(query,2, list => { this.memberUserOptions = list; });
        },
          
    /** 搜索用户 */
        searchUserBase(query,type) {
          console.log('搜索用户:', query)
          this.currentSearchQuery = query
          this.userPageNum = 1
          this.userHasMore = true
          
          if (query !== '') {
            this.userLoading = true
            console.log('调用用户搜索接口')
            listUser({
              pageNum: this.userPageNum,
              pageSize: this.userPageSize,
              name: query,
              deleted: 0
            }).then(response => {
              console.log('搜索结果:', response)
              if(type == 1){
                this.userOptions = response.rows || []
                this.userTotal = parseInt(response.total) || 0  // 确保是数字类型
                this.userHasMore = this.userOptions.length < this.userTotal
                this.userLoading = false
              }else{
                this.memberUserOptions = response.rows || []
                this.memberUserTotal = parseInt(response.total) || 0  // 确保是数字类型
                this.memberUserHasMore = this.memberUserOptions.length < this.memberUserTotal
                this.memberUserLoading = false
              }
          
            }).catch(error => {
              console.error('搜索失败:', error)
              this.userOptions = []
              this.userHasMore = false
              this.userLoading = false
            })
          } else {
            this.loadInitialUsers()
          }
        },
        /** 初始化用户列表 */
        initUserOptions() {
          this.loadInitialUsers()
        },
        /** 加载初始用户列表 */
        loadInitialUsers() {
          this.userLoading = true
          this.userPageNum = 1
          this.currentSearchQuery = ''
          
          listUser({
            pageNum: this.userPageNum,
            pageSize: this.userPageSize,
            deleted: 0
          }).then(response => {
            this.userOptions = response.rows || []
            this.userTotal = parseInt(response.total) || 0
            this.userHasMore = this.userOptions.length < this.userTotal
            this.userLoading = false
          }).catch(() => {
            this.userOptions = []
            this.userHasMore = false
            this.userLoading = false
          })
        },
        
        /** 加载更多用户 */
        loadMoreUsers() {
          if (this.userLoading || !this.userHasMore) {
            return
          }
          
          this.userLoading = true
          this.userPageNum += 1
          
          const params = {
            pageNum: this.userPageNum,
            pageSize: this.userPageSize,
            deleted: 0
          }
          
          // 如果有搜索关键字，添加搜索条件
          if (this.currentSearchQuery) {
            params.name = this.currentSearchQuery
          }
          
          listUser(params).then(response => {
            const newUsers = response.rows || []
            this.userOptions = [...this.userOptions, ...newUsers]
            this.userTotal = parseInt(response.total) || 0
            this.userHasMore = this.userOptions.length < this.userTotal
            this.userLoading = false
          }).catch(() => {
            this.userPageNum -= 1 // 回退页码
            this.userLoading = false
          })
        },
        
        /** 处理下拉框显示状态变化 */
        handleUserSelectVisible(visible) {
          if (visible && this.userOptions.length === 0) {
            this.loadInitialUsers()
          }
        },
      handleMemberSelectVisible(visible) {
          if (visible && this.userOptions.length === 0) {
            this.loadInitialUsers()
          }
        },
        /** 初始化用户列表 */
        initUserOptions() {
          this.userLoading = true
          listUser({
            pageNum: 1,
            pageSize: 50,
            deleted: 0
          }).then(response => {
            this.userOptions = response.rows || []
            this.userLoading = false
          }).catch(() => {
            this.userOptions = []
            this.userLoading = false
          })
        }
      },
      mounted() {
        this.initUserOptions()
      },
      computed: {
        /** 上传参数 */
        upload() {
          return {
            headers: { Authorization: "Bearer " + this.getToken() },
            url: process.env.VUE_APP_BASE_API + "/common/upload"
          }
        }
      }
  }
  

</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  display: block;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-url-display {
  margin-top: 8px;
  text-align: center;
}
</style>

